<!DOCTYPE html>
<html lang="en">

	<head>
		<meta charset="UTF-8">
		<title>html转成图片</title>
		<script src="jquery-3.2.1.min.js"></script>
		<script src="html2canvas.js"></script>
		<script src="canvas2image.js"></script>
	</head>
	<style>
		.main {
			width: 40%;
			float: left;
			background: white;
			color: black
		}
		
		.btn {
			width: 100px;
			height: 40px;
			line-height: 40px;
			text-align: center;
			color: #fff;
			background: red;
		}
	</style>

	<body>

		<div class="btn">点击截图</div>
		<div id="targetDom" class="main">
			<div style="padding: 0 0.5rem 0.5rem; text-align: center;">
				<h2>哈哈哈</h2>
				<hr />
				<p>我在测试</p>
				<p>我真的在测试</p>
				<p>呀哈，你在测试</p>
				<p>嗯哪，我在测试</p>
				<img width="200" class="img">
				<p>结束了，ending</p>
			</div>
		</div>
		<img id="screenShotImg">
	</body>
	<script>
		//加载图片
		$.ajax({
			type: "POST",
			dataType: 'json',
			url: '/picture/tbPictureController.do?selectPictures',
			xhrFields: {
				withCredentials: true
			},
			crossDomain: true,
			data: {
				pageNo: 1,
				pageSize: 1
			},
			cache: false,
			success: function(data) {
				var rows = data.rows;
				$('.img').attr('src', rows[0].uploadfilepath)
			}

		})
		//生成图片
		document.querySelector('.btn').onclick = function() {
			var url = $('.img').attr('src');
			//将图片转成base64
			$.ajax({
				type: "POST",
				dataType: 'json',
				url: '/picture/tbPictureController.do?transById',
				xhrFields: {
					withCredentials: true
				},
				crossDomain: true,
				data: {
					url: url
				},
				cache: false,
				success: function(data) {
					var base64 = data.rows;
					$('.img').attr('src', base64);
					screenShot($('#targetDom'), function(canvas, width, height) {
						document.querySelector('#screenShotImg').src = canvas;
						document.querySelector('#screenShotImg').style.width = width + "px";
						document.querySelector('#screenShotImg').style.height = height + "px";
					});
				}

			})

		};

		/**
		 * 截图功能
		 * targetDom 要克隆的目标dom元素
		 * cb 回调函数
		 */
		function screenShot(targetDom, cb) {
			var copyDom = targetDom.clone(); //克隆dom节点
			copyDom.css('display', 'block');
			$('body').append(copyDom); //把copy的截图对象追加到body后面
			var width = copyDom.width(); //dom宽
			var height = copyDom.height(); //dom高
			var scale = 3; //放大倍数
			var canvas = document.createElement('canvas');
			canvas.width = width * scale; //canvas宽度
			canvas.height = height * scale; //canvas高度
			var content = canvas.getContext("2d");
			content.scale(scale, scale);
			var rect = copyDom.get(0).getBoundingClientRect(); //获取元素相对于视察的偏移量
			content.translate(-rect.left, -rect.top); //设置context位置，值为相对于视窗的偏移量负值，让图片复位
			html2canvas(copyDom, {
				allowTaint: true,
				tainTest: true,
				scale: scale,
				canvas: canvas,
				width: width,
				heigth: height,
				onrendered: function(canvas) {
					if(cb) {
						copyDom.css('display', 'none');
						cb(canvas.toDataURL("image/png"), width, height);
					}
				}
			});
		}
	</script>

</html>